package xyz.fivefaith.cloud.common.sentinel;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.cloud.sentinel.SentinelProperties;
import com.alibaba.cloud.sentinel.custom.SentinelAutoConfiguration;
import com.alibaba.csp.sentinel.init.InitExecutor;
import com.alibaba.csp.sentinel.transport.config.TransportConfig;

import jakarta.annotation.Resource;

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Bean;

import xyz.fivefaith.tool.common.constant.StringPool;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Lion Li
 */
@AutoConfiguration(before = SentinelAutoConfiguration.class)
@EnableConfigurationProperties({SentinelProperties.class, SentinelCustomProperties.class})
public class SentinelCustomAutoConfiguration {

    @Resource private SentinelProperties properties;
    @Resource private SentinelCustomProperties customProperties;
    @Resource private DiscoveryClient discoveryClient;

    @Bean
    public Object sentinelInit() {
        if (StringUtils.isNotBlank(customProperties.getServerName())) {
            List<ServiceInstance> instances =
                    discoveryClient.getInstances(customProperties.getServerName());
            String serverList =
                    instances.stream()
                            .map(
                                    instance ->
                                            String.format(
                                                    "http://%s:%s",
                                                    instance.getHost(), instance.getPort()))
                            .collect(Collectors.joining(StringPool.COMMA));
            System.setProperty(TransportConfig.CONSOLE_SERVER, serverList);
        } else {
            if (StringUtils.isEmpty(System.getProperty(TransportConfig.CONSOLE_SERVER))
                    && StringUtils.isNotBlank(properties.getTransport().getDashboard())) {
                System.setProperty(
                        TransportConfig.CONSOLE_SERVER, properties.getTransport().getDashboard());
            }
        }
        // 手动初始化 sentinel
        InitExecutor.doInit();
        return new Object();
    }
}
